<template>
    <van-swipe-cell>
        <div class="cart-item">
            <van-checkbox v-model="checked"/>
            <div class="cart-item-content">
                <wing-blank>
                    <van-image class="cart-item-image" :width="90" :radius="4" :src="item.imageUrl"
                               @click.stop="handleRouteToProduct"/>
                </wing-blank>
                <div class="cart-item-right">
                    <van-row>
                        <van-col span="24">
                            <span class="van-multi-ellipsis--l2 cart-item-name"
                                  @click.stop="handleRouteToProduct">{{item.name}}</span>
                        </van-col>
                    </van-row>
                    <white-space/>
                    <div class="cart-item-option-selections-action" @click="$emit('option-selections-click', item)">
                        <span class="van-ellipsis cart-item-option-selections-stringify">{{optionSelectionsStringify}}</span>
                        <van-icon name="arrow-down"/>
                    </div>
                    <white-space/>
                    <van-row type="flex" justify="space-between" align="center">
                        <van-col span="12">
                            <price :value="item.price" :size="18"/>
                        </van-col>
                        <van-col span="12">
                            <div class="cart-item-quantity">
                                <van-stepper :value="item.quantity"
                                             @change="handleAdjustCartItemQuantity" button-size="20px"/>
                            </div>
                        </van-col>
                    </van-row>
                </div>
            </div>
        </div>
        <template #right>
            <van-button class="cart-item-swipe-button" square type="danger" text="删除"
                        :loading="deleteLoading"
                        @click.stop="handleRemoveItem"/>
        </template>
    </van-swipe-cell>
</template>

<script>
  import { Button, Checkbox, Col, Icon, Image, Row, Stepper, SwipeCell, Toast } from "vant"
  import WingBlank from "@/components/WingBlank"
  import * as _ from "lodash"
  import WhiteSpace from "@/components/WhiteSpace"
  import Price from "@/components/Price"
  import { createNamespacedHelpers } from "vuex"
  import { message } from "@mall/api-services"

  const { mapActions } = createNamespacedHelpers("cart")
  export default {
    name: "CartItem",
    components: {
      Price,
      WhiteSpace,
      WingBlank,
      [Button.name]: Button,
      [Checkbox.name]: Checkbox,
      [Col.name]: Col,
      [Icon.name]: Icon,
      [Image.name]: Image,
      [Row.name]: Row,
      [Stepper.name]: Stepper,
      [SwipeCell.name]: SwipeCell,
    },
    props: {
      item: {
        type: Object,
      },
    },
    computed: {
      optionSelectionsStringify() {
        const { item } = this
        const { optionSelections } = item
        return _.chain(optionSelections).map(selection => selection.value).join(", ").value()
      },
      checked: {
        get: function() {
          const { item } = this
          return item.checked
        },
        set: function(checked) {
          const { item, checkItem, uncheckItem } = this
          Toast.loading()
          new Promise((resolve, reject) => {
            if (checked) {
              checkItem(item.id).then(resolve).catch(reject)
            } else {
              uncheckItem(item.id).then(resolve).catch(reject)
            }
          })
            .catch(({ response }) => Toast(message.getResponseMessage(response)))
            .finally(() => Toast.clear())
        },
      },
    },
    data() {
      return {
        deleteLoading: false,
      }
    },
    methods: {
      ...mapActions(["checkItem", "uncheckItem", "adjustCartItemQuantity", "removeItems"]),
      handleRouteToProduct() {
        const { item } = this
        this.$router.push(`/products/${item.productId}`)
      },
      handleAdjustCartItemQuantity(newQuantity) {
        const { item } = this
        const quantityDelta = newQuantity - item.quantity
        Toast.loading()
        this.adjustCartItemQuantity({ itemId: item.id, quantityDelta })
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => Toast.clear())
      },
      handleRemoveItem() {
        const { item } = this
        this.deleteLoading = true
        this.removeItems([item.id])
          .then(() => Toast("删除成功"))
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.deleteLoading = false)
      },
    },
  }
</script>

<style lang="scss" scoped>
    @import "../../styles/variables";

    .cart-item {
        display: flex;
        align-items: center;
        margin: 9px;
    }

    .cart-item-image {
        box-shadow: 0 8px 12px #ebedf0;
    }

    .cart-item-content {
        flex: 1;
        display: flex;
        width: calc(100% - 20px);

        .cart-item-right {
            width: calc(100% - 90px - 18px);
        }

        .cart-item-name {
            line-height: 1.2rem;
            font-size: 14px;
        }

        .cart-item-option-selections-action {
            display: inline-flex;
            align-items: center;
            padding: 2px 4px;
            font-size: 14px;
            border-radius: 4px;
            background: $gray-2;
            color: $gray-6;
            max-width: calc(100% - 8px);

            .cart-item-option-selections-stringify {
                display: inline-block;
                margin-right: 4px;
                flex: 1;
            }
        }

        .cart-item-quantity {
            display: flex;
            justify-content: flex-end;
        }
    }

    .cart-item-swipe-button {
        height: 100%;
    }

</style>
